﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using log4net;
using WHW_NetUtility;
using MotionControl;
using System.Threading;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using HalconDotNet;

namespace MainFrame
{
    public partial class frm_MainFrame : Form
    {
        string path_Save = Environment.CurrentDirectory + "\\CSV";

        FormManual frmManual;//型号数据
        FormConfig frmConfig;//相机数据
        FormRunStatus frmRunStatus;//相机数据
        frm_Main frmAxisConfig;//运动设置
        FormMainPage MainPage;
        //FormCalibration frmCalib;//系统标定
        FormUserManage frmUserM;//用户管理
        FormLogin myLogin;//登陆窗口

        Thread formInfoDisplay_T;//界面信息显示
        Thread warningErrorTips_T;//警告弹窗和错误弹窗监控
      
        Thread buttonControl_T;//按钮控制
   

        //全局时间
        Stopwatch totalTimeSW = new Stopwatch();//软件开启到现在的时间
        Stopwatch runTimeSW = new Stopwatch();//自动运动的时间
        Stopwatch LastTimeSW = new Stopwatch();//上次运行的时间


        ManualResetEvent autoMRE = new ManualResetEvent(false);

        public const double paperPerDistance = 24.086;//拉砂纸电机的速度 24.086mm/s

        Stopwatch waitLaminteSW = new Stopwatch();

        //int pullTempCount = 0;//拉料临时计数，用于打印报警日志
        //int takeTempCount = 0;//撕膜临时计数，用于打印报警日志
        //int takeTempCount_BackMany = 0;
        //int onlyPullTimes = 1;//排空次数
        //int takeTempCount_BackMore = 0;

        private string saveFilePath = Environment.CurrentDirectory + "\\" + "statisticsInfo.sta";//设置数量保存路径
        private Stopwatch axisSW=new Stopwatch();

        private bool is_hsmc_1_grayValue_display = false;//灰度是否显示
        private bool is_hsmc_2_grayValue_display = false;//灰度是否显示
        public frm_MainFrame()
        {
            InitializeComponent();
    
            loadTips.loadTipsInLogin("加载主窗体");
        }

        private void threadPoolSet()
        {
            try
            {
                int workThread_min = 0, IOthread_min = 0;
                int workThread_max = 0, IOthread_max = 0;

                ThreadPool.GetMinThreads(out workThread_min, out IOthread_min);
                ThreadPool.GetMaxThreads(out workThread_max, out IOthread_max);
                displalyInfo.displayInfoMain($"线程池默认最小、最大线程数量：[{workThread_min}-{IOthread_min}]、[{workThread_max}-{IOthread_max}]");
                //MessageDisplay($"线程池默认最大线程数量：{workThread_max}-{IOthread_max}");
                ThreadPool.SetMinThreads(workThread_max - 10, IOthread_max - 5);
                ThreadPool.GetMinThreads(out workThread_min, out IOthread_min);
                //tbx_thread_number_all.Text = workThread_min.ToString();
                displalyInfo.displayInfoMain($"线程池修改后最小线程数量：{workThread_min}-{IOthread_min}");
                //MessageDisplay($"线程池修改后最大线程数量：{workThread_max}-{IOthread_max}");
            }
            catch (System.Exception ex)
            {
                MessageDisplay($"设置线程出错：{ex}");
                Log4Helper.WriteLog("threadPoolSet", ex);
            }

        }

        private void frm_MainFrame_Load(object sender, EventArgs e)
        {
            try
            {
                GlobalMotion.AxisHome+= GlobalMotion.GoHome_Await;
                Log4Helper.init();
                int hegihtView = Screen.PrimaryScreen.Bounds.Height;
                int hegihtWork = Screen.PrimaryScreen.WorkingArea.Height;
                #region 视觉矫正参数
                visionProc. hv_CameraParameters = new HTuple();
                visionProc.hv_CameraParameters[0] = "area_scan_division";
                //visionProc.hv_CameraParameters[1] = 7.20549e-05;
                //visionProc.hv_CameraParameters[2] = -2018.14;
                //visionProc.hv_CameraParameters[3] = 2.40073e-06;
                //visionProc.hv_CameraParameters[4] = 2.4e-06;
                //visionProc.hv_CameraParameters[5] = 2744.64;
                //visionProc.hv_CameraParameters[6] = 1707.22;
                //visionProc.hv_CameraParameters[7] = 5472;
                //visionProc.hv_CameraParameters[8] = 3648;
                visionProc.hv_CameraParameters[1] = 0.0157154;
                visionProc.hv_CameraParameters[2] = -1842.42;
                visionProc.hv_CameraParameters[3] = 2.40224e-06;
                visionProc.hv_CameraParameters[4] = 2.4e-06;
                visionProc.hv_CameraParameters[5] = 2716.02;
                visionProc.hv_CameraParameters[6] = 1703.52;
                visionProc.hv_CameraParameters[7] = 5472;
                visionProc.hv_CameraParameters[8] = 3648;
                HOperatorSet.ChangeRadialDistortionCamPar("adaptive", visionProc.hv_CameraParameters, 0,
             out visionProc.hv_CameraZero);
                HOperatorSet.ReadObject(out visionProc.mapObject, Application.StartupPath + "\\mapObj.hobj");
                #endregion
                displalyInfo.displayInfoMain+= MessageDisplay;//关联信息提示全局变量
                displalyInfo.displayInfoMainBox += MessageDisplay;//关联信息提示全局变量
                displalyInfo.displayErrorMain = AlarmMessageDisplay;//关联信息提示全局变量
                MotionControl.GlobalVariable.MessageDisplay = MessageDisplay;//不同工程间的信息提示
                changeUser.changeUserMain += UserLogin;
                GlobalVar.btn_Start = btn_StartProccess;
                GlobalVar.btn_Home = btn_HomeProccess;
                GlobalVar.btn_Estop = btn_EstopProccess;
                displalyInfo.displayInfoMain("程序启动");
                loadTips.loadTipsInLogin("加载主窗体");
                threadPoolSet();//线程设置
                totalTimeSW.Start();//全局计时开始
                GlobalVar.isExit = false;
                #region load close software data
                try
                {
                    GlobalVar.closeSave=(closeStartConifg)SerializeHelper.DeserializeFile<closeStartConifg>(GlobalVar.closeSavePath, "关闭保存") ;//串口数据反序列化
                    if (GlobalVar.closeSave == null)
                        GlobalVar.closeSave = new closeStartConifg();
                    if (!string.IsNullOrEmpty(GlobalVar.closeSave.CurrentTypeName))
                        GlobalVar.currentSelectTypeName = GlobalVar.closeSave.CurrentTypeName;
               
                }
                catch (System.Exception ex)
                {
                    displalyInfo.displayInfoMain("载入上次关闭时保存的文件失败：" + ex.Message);
                    Log4Helper.WriteLog(ex);
                }
                #endregion
                #region 用户身份
                UserLogin();
                #endregion
                #region serial port init
                loadTips.loadTipsInLogin("串口初始化");
                GlobalVar.userConfig = (ConfigData)SerializeHelper.DeserializeFile<ConfigData>(GlobalVar.configPath, "用户配置数据") ;//串口数据反序列化
                #endregion
                #region camera Image Display
                GlobalVar.imageDisplay1 = ImageDisplay_1;
                GlobalVar.imageDisplay1_obj = ImageDisplay_1_obj;
                GlobalVar.Image_drawRoiRegion1 = DrawRoiRegion1;
                GlobalVar.Image_clearRoiRegion1 = ClearRoiRegion1;
              

                GlobalVar.imageDisplay2 = ImageDisplay_2;
                GlobalVar.imageDisplay2_obj = ImageDisplay_2_obj;
                GlobalVar.Image_drawRoiRegion2 = DrawRoiRegion2;
                GlobalVar.Image_clearRoiRegion2 = ClearRoiRegion2;

                GlobalVar.imageDisplay3 = ImageDisplay_3;
                GlobalVar.imageDisplay3_obj = ImageDisplay_3_obj;
                GlobalVar.Image_drawRoiRegion3 = DrawRoiRegion3;
                GlobalVar.Image_clearRoiRegion3 = ClearRoiRegion3;
                #endregion
                #region 窗口设置
                loadTips.loadTipsInLogin("加载数据显示窗体");
                //窗口设置--类型数据
                loadTips.loadTipsInLogin("加载手动操作窗体");
                if (frmManual == null || frmManual.IsDisposed)
                {
                    frmManual = new FormManual();
                    frmManual.TopLevel = false;
                    frmManual.FormBorderStyle = FormBorderStyle.None;
                    pl_main.Controls.Add(frmManual);
                    frmManual.StartPosition = FormStartPosition.CenterParent;
                }
                //窗口设置--类型数据
                loadTips.loadTipsInLogin("加载软件配置窗体");
                if (frmConfig == null || frmConfig.IsDisposed)
                {
                    frmConfig = new FormConfig();
                    frmConfig.TopLevel = false;
                    frmConfig.FormBorderStyle = FormBorderStyle.None;
                    pl_main.Controls.Add(frmConfig);
                    frmConfig.StartPosition = FormStartPosition.CenterParent;
                   
                }
                if (frmAxisConfig == null || frmAxisConfig.IsDisposed)
                {
                    frmAxisConfig = new frm_Main();
                    frmAxisConfig.TopLevel = false;
                    frmAxisConfig.FormBorderStyle = FormBorderStyle.None;
                    pl_main.Controls.Add(frmAxisConfig);
                    frmAxisConfig.StartPosition = FormStartPosition.CenterParent;
                    frmAxisConfig.Show();
                }
               
                //窗口设置--通讯设置
                //窗口设置--用户管理
                loadTips.loadTipsInLogin("加载用户管理窗体");
                if (frmUserM == null || frmUserM.IsDisposed)
                {
                    frmUserM = new FormUserManage();
                    frmUserM.TopLevel = false;
                    frmUserM.FormBorderStyle = FormBorderStyle.None;//隐藏边框
                    pl_main.Controls.Add(frmUserM);
                }
                if (frmRunStatus == null || frmRunStatus.IsDisposed)
                {
                    frmRunStatus = new FormRunStatus();
                    frmRunStatus.TopLevel = false;
                    frmRunStatus.FormBorderStyle = FormBorderStyle.None;//隐藏边框
                    pl_main.Controls.Add(frmRunStatus);
                }
             
                if(MainPage==null|| MainPage.IsDisposed)
                {
                    MainPage = new FormMainPage();
                    MainPage.TopLevel = false;
                    MainPage.FormBorderStyle = FormBorderStyle.None;
                    panel3.Controls.Add(MainPage);
                    MainPage.StartPosition = FormStartPosition.CenterParent;
                    MainPage.Dock = DockStyle.Fill;
                }
                #endregion
                
                loadTips.loadTipsInLogin("窗口初始化");
                #region 弹窗条件初始化
                //弹窗条件初始化
                for (int i = 0; i < GlobalVar.errorTips.Length; i++)
                {
                    GlobalVar.errorTips[i] = new warningErrorInfo();
                }
                for (int i = 0; i < GlobalVar.warningTips.Length; i++)
                {
                    GlobalVar.warningTips[i] = new warningErrorInfo();
                }
                #endregion
                loadTips.loadTipsInLogin("IO窗口设定");
                #region 控制卡检测
                GlobalVar.isHardStart = GlobalMotion.cardInit();
             
                #endregion
                showHideWin(e_Win.设备点动);
                showHideWin(e_Win.程序配方);
                showHideWin(e_Win.控制卡设置);
                ShowPage("主页");
                loadTips.loadTipsInLogin("线程设定");
                if (MotionControl.GlobalVariable.isCardStart[0])
                {
                    #region 线程启动


                    Task.Factory.StartNew(GlobalMotion.Task_ReadInput);
                    Task.Factory.StartNew(GlobalMotion.Task_ConverFront);
                    Task.Factory.StartNew(GlobalMotion.Task_ConveryCut);
                 

                    Task.Factory.StartNew(GlobalMotion.Task_ConveryLabel);
                    Task.Factory.StartNew(GlobalMotion.Task_FlyLabel1);
                    Task.Factory.StartNew(GlobalMotion.Task_FlyLabel2);
                    Task.Factory.StartNew(GlobalMotion.Task_Cuting);
                    Task.Factory.StartNew(GlobalMotion.Task_Labeling);
                    Task.Factory.StartNew(GlobalMotion.Task_ConveryDown);
                    Task.Factory.StartNew(GlobalMotion.Task_ConveryDownCheck);
                    Task.Factory.StartNew(GlobalMotion.Task_NGConvery);
                    Task.Factory.StartNew(GlobalMotion.Task_ConveryUp);
                    Task.Factory.StartNew(GlobalMotion.Task_ProductState);
                    Task.Factory.StartNew(GlobalMotion.Task_CheckPCS);
                    Task.Factory.StartNew(GlobalMotion.Task_air);
                    Task.Factory.StartNew(GlobalMotion.Task_air_cut);
                    Thread.Sleep(100);
                    Task.Factory.StartNew( GlobalMotion.ButtonControl);
                    Task.Factory.StartNew(formInfoDisplay);
                    Task.Factory.StartNew(GlobalMotion.Task_LightDisplay);
                    Task.Factory.StartNew(GlobalMotion.Task_MesTcp);
                    Task.Factory.StartNew(GlobalMotion.Task_MesUrl);
                    Task.Factory.StartNew(GlobalMotion.Task_ConverMan);
                    #endregion
                }
                DiskCheck();
                tssl_startTime_status.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                #region 定位相机图片显示
                var imgDir1 = Environment.CurrentDirectory + $"\\saveImage\\{e_CameraPlate.定位相机平台1.ToString()}";
                var fs1 = Directory.GetFiles(imgDir1);
                if (fs1.Length > 0)
                {
                    HOperatorSet.ReadImage(out visionProc.srcObject_pos, fs1[0]);
                    GlobalVar.imageDisplay1(visionProc.srcObject_pos);
                }
                var imgDir2 = Environment.CurrentDirectory + $"\\saveImage\\{e_CameraPlate.图案相机平台1.ToString()}";
                var fs2 = Directory.GetFiles(imgDir2);
                if (fs2.Length > 0)
                {
                    HOperatorSet.ReadImage(out visionProc.srcObject_scan, fs2[0]);
                    GlobalVar.imageDisplay2(visionProc.srcObject_scan);
                }
                var imgDir3 = Environment.CurrentDirectory + $"\\saveImage\\{e_CameraPlate.检测相机平台1.ToString()}";
                var fs3 = Directory.GetFiles(imgDir3);
                if (fs3.Length > 0)
                {
                    HOperatorSet.ReadImage(out visionProc.srcObject_ckeck, fs3[0]);
                    GlobalVar.imageDisplay3(visionProc.srcObject_ckeck);
                }


                visionProc.ReadRegion();
                visionProc.ROI1 = visionProc.ROI_List[(int)e_CameraPlate.定位相机平台1];
                visionProc.ROI2 = visionProc.ROI_List[(int)e_CameraPlate.图案相机平台1];
                visionProc.ROI_M_List1 = visionProc.ReadRegion_M(e_CameraPlate.检测相机平台1);
                visionProc.ROI_M_List2 = visionProc.ReadRegion_M(e_CameraPlate.检测相机平台2);
                GlobalVar.imageDisplay1_obj(visionProc.ROI1.ROI_Region,"green");
                GlobalVar.imageDisplay1_obj(visionProc.ROI1.ROI_Template,"blue");

                GlobalVar.imageDisplay2_obj(visionProc.ROI2.ROI_Region, "green");
                GlobalVar.imageDisplay2_obj(visionProc.ROI2.ROI_Template, "blue");

                visionProc.ReadTemplateRegion();
               for(int m=0;m< visionProc.ROI_M_List1.Count;m++)
                {
                    GlobalVar.imageDisplay3_obj(visionProc.ROI_M_List1[m], "green");
                }
                for (int m = 0; m < visionProc.ROI_M_List2.Count; m++)
                {
                    GlobalVar.imageDisplay3_obj(visionProc.ROI_M_List2[m], "green");
                }
                #endregion
                Task.Run(ConnectSQL);
                GlobalMotion.CardExt_2.setOut((ushort)e_output_extCard2.LED照明灯, e_out_OnOff.off);
                ckb_IsSaftGate.Checked = GlobalVar.closeSave.IsSaftGate;
                this.ckb_IsSaftGate.CheckedChanged += new System.EventHandler(this.ckb_IsSaftGate_CheckedChanged);
                Task.Run(new Action(()=> { 
                if(GlobalVar.userConfig.UploadInfo.IsUploadUrl)
                    {
                        if(!string.IsNullOrEmpty(GlobalVar.userConfig.UploadInfo.url_GetDate))
                        {
                            UploadInterface.upload_GetDate();
                        }
                    }
                
                }));
              //  HOperatorSet.ReadObject(out visionProc.mapObject,Application.StartupPath+ "\\mapObj.hobj");
            }
            catch (System.Exception ex)
            {
                MessageDisplay("程序启动异常：" + ex.Message);
            }
            
        }
      
        private void ConnectSQL()
        {
            GlobalVar.sqlHelper = new sqlHelperDapper(dbType.mysql, GlobalVar.userConfig.db_Name, GlobalVar.userConfig.db_UserName,
                GlobalVar.userConfig.db_Password, GlobalVar.userConfig.db_IP);
            
        }
        /// <summary>
        /// 开机第一次点启动需要整机回零
        /// </summary>
        private bool IsOpenReset = false;
      
       
        public void UserLogin()
        {

                this.Invoke(new Action(() => {

                    if (MotionControl.GlobalVariable.OperLevel == (int)MotionControl.operLevel.operatorStaff)//操作原
                    {
                        btn_type.Visible = false;//参数
                        btn_camera.Visible = false;//调试
                        btn_MotionControl.Visible = false;//控制卡
                        btn_useManage.Visible = false;//用户管理
                        panel1.Visible = false;//手动信号
                        tssl_permissionAndUserName_status.Text = $"操作员,{MotionControl.GlobalVariable.OperName}";
                    }
                    else if (MotionControl.GlobalVariable.OperLevel == (int)MotionControl.operLevel.technician)//技术
                    {
                        btn_type.Visible = true;//参数
                        btn_camera.Visible = true;//调试
                        btn_MotionControl.Visible = false;//控制卡
                        btn_useManage.Visible = false;//用户管理
                        panel1.Visible = true;//手动信号
                        tssl_permissionAndUserName_status.Text = $"技术员,{MotionControl.GlobalVariable.OperName}";
                    }
                    else if (MotionControl.GlobalVariable.OperLevel == (int)MotionControl.operLevel.admin)//技术
                    {
                      
                        btn_type.Visible = true;//参数
                        btn_camera.Visible = true;//调试
                        btn_MotionControl.Visible = true;//控制卡
                        btn_useManage.Visible = true;//用户管理
                        panel1.Visible = true;//手动信号
                        tssl_permissionAndUserName_status.Text = $"管理员,{MotionControl.GlobalVariable.OperName}";
                    }
                    else if (MotionControl.GlobalVariable.OperLevel == (int)MotionControl.operLevel.superAdmin)//超级
                    {

                        btn_type.Visible = true;//参数
                        btn_camera.Visible = true;//调试
                        btn_MotionControl.Visible = true;//控制卡
                        btn_useManage.Visible = true;//用户管理
                        panel1.Visible = true;//手动信号
                        tssl_permissionAndUserName_status.Text = $"超级管理员,{MotionControl.GlobalVariable.OperName}";
                    }
                }));
       
           
        }

       

        public void DiskCheck()
        {
            try
            {
                string diskName = Application.StartupPath.Substring(0, 1);
                long disk = HardwareInfo.GetHardDiskSpace(diskName);
                long diskFree_L = HardwareInfo.GetHardDiskFreeSpace(diskName);
                double precent_d = Convert.ToDouble((disk - diskFree_L)) / disk;
                string precent = (Math.Round(precent_d, 2)).ToString("P0");

                if (InvokeRequired)
                {
                    this.BeginInvoke(new Action(() =>
                    {
                        tspb_diskInfo.Maximum = 100;
                        tspb_diskInfo.Minimum = 0;

                        if (precent_d > 0.9)
                        {
                            tspb_diskInfo.ForeColor = Color.Red;
                            tssl_diskInfoPrecent_status.BackColor = Color.Red;
                        }
                        else if (precent_d > 0.7)
                        {
                            tspb_diskInfo.ForeColor = Color.Yellow;
                            tssl_diskInfoPrecent_status.BackColor = Color.Yellow;
                        }
                        else
                        {
                            tspb_diskInfo.ForeColor = Color.Green;
                            tssl_diskInfoPrecent_status.BackColor = Color.Green;
                        }
                        tspb_diskInfo.Value = (int)(precent_d*100);
                        tssl_diskInfoPrecent_status.Text = precent;
                    }));
                }
                else
                {
                    tspb_diskInfo.Maximum = 100;
                    tspb_diskInfo.Minimum = 0;

                    if (precent_d > 0.9)
                    {
                        tspb_diskInfo.ForeColor = Color.Red;                   
                        tssl_diskInfoPrecent_status.BackColor = Color.Red;
                    }
                    else if (precent_d > 0.7)
                    {
                        tspb_diskInfo.ForeColor = Color.Yellow;
                        tssl_diskInfoPrecent_status.BackColor = Color.Yellow;
                    }
                    else
                    {
                        tspb_diskInfo.ForeColor = Color.Green;
                        tssl_diskInfoPrecent_status.BackColor = Color.Green;
                    }
                    tspb_diskInfo.Value = (int)(precent_d * 100);
                    tssl_diskInfoPrecent_status.Text = precent;
                }
            }
            catch (System.Exception ex)
            {
                MessageDisplay("获取软件所在硬盘信息异常:" + ex.Message);
                Log4Helper.WriteLog(ex);
            }
        }

        /// <summary>
        /// 在信息框写入提示信息
        /// </summary>
        /// <param name="message"></param>
        public void MessageDisplay(string message)
        {
            try
            {
                    rbx_displayMessage.BeginInvoke(new MethodInvoker(() =>
                    {
                        if (rbx_displayMessage.Lines.Length>2000)
                        {
                            rbx_displayMessage.Text = "";
                        }
                        DateTime NowTime = DateTime.Now;
                        rbx_displayMessage.AppendText(NowTime.ToString("yyyy/MM/dd HH:mm:ss.fff") + "  " + message + Environment.NewLine);
                        rbx_displayMessage.ScrollToCaret();
                    }));
                Log4Helper.WriteLog("界面信息", message);
            }
            catch (Exception)
            {
            }
            
        }
        public void AlarmMessageDisplay(string message)
        {
            try
            {
                string str = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff") + "  " + message + Environment.NewLine;
                rbx_displayMessage.BeginInvoke(new MethodInvoker(() =>
                {
                    if (rbx_displayMessage.Text.Length > 10000)
                    {
                        rbx_displayMessage.Text = "";
                    }
                    rbx_displayMessage.SelectionColor = Color.Red;
                    rbx_displayMessage.SelectedText = str;
                    rbx_displayMessage.ScrollToCaret();
                  
                }));
                Log4Helper.WriteLogError(message);
            }
            catch (Exception)
            {
            }

        }

        /// <summary>
        /// 在信息框写入提示信息
        /// </summary>
        /// <param name="message"></param>
        public void MessageDisplay(string message,string english="")
        {
            try
            {

                rbx_displayMessage.BeginInvoke(new MethodInvoker(() =>
                    {
                        if (rbx_displayMessage.Text.Length > 5000)
                        {
                            rbx_displayMessage.Text = "";
                        }
                        DateTime NowTime = DateTime.Now;
                        rbx_displayMessage.AppendText(NowTime.ToString("yyyy/MM/dd HH:mm:ss.fff") + "  " + message + Environment.NewLine);
                        rbx_displayMessage.ScrollToCaret();
                    }));
                
              

                Log4Helper.WriteLog("界面信息", message);
            }
            catch (Exception)
            {
            }

        }
        /// <summary>
        /// 在信息框写入提示信息
        /// </summary>
        /// <param name="message"></param>
      
      
        /// <summary>
        /// 显示隐藏窗口
        /// </summary>
        /// <param name="winNumber">窗口对应的ID号</param>
        public void showHideWin(e_Win curWin)
        {
            try
            {
                switch (curWin)
                {
                    case e_Win.设备历史:
                        frmManual.Hide();
                        frmAxisConfig.Hide();
                        frmConfig.Hide();
                        frmRunStatus.Hide();
                        frmUserM.Hide();
                        break;
                    case e_Win.程序配方:
                        frmManual.Show();
                        frmAxisConfig.Hide();
                        frmConfig.Hide();
                        frmRunStatus.Hide();
                        frmUserM.Hide();
                        break;
                    case e_Win.控制卡设置:
                        frmManual.Hide();
                        frmAxisConfig.Show();
                        frmConfig.Hide();
                        frmRunStatus.Hide();
                        frmUserM.Hide();
                        break;
                    case e_Win.设备IO:
                        
                        frmManual.Hide();
                        frmAxisConfig.Hide();
                     
                        frmConfig.Hide();
                        frmRunStatus.Hide();
                        frmUserM.Hide();
                        break;
                    case e_Win.设备点动:
                        
                        frmManual.Hide();
                        frmAxisConfig.Hide();
                        frmConfig.Show();
                        frmRunStatus.Hide();
                        frmUserM.Hide();
                        break;
                    case e_Win.设备状态:
                        frmRunStatus.Show();
                        frmManual.Hide();
                        frmAxisConfig.Hide();
                        frmConfig.Hide();
                        frmUserM.Hide();
                        break;
                    case e_Win.用户管理:
                        frmManual.Hide();
                        frmAxisConfig.Hide();
                        frmConfig.Hide();
                        frmRunStatus.Hide();
                        frmUserM.Show();
                        break;

                    default:
                        break;
                }
            }catch(Exception ex)
            {
                displalyInfo.displayErrorMain(ex.Message);
            }
         }
     
        /// <summary>
        /// 界面更新函数
        /// </summary>
        private void formInfoDisplay()
        {
            try
            {
                Stopwatch tempSw = new Stopwatch();
                while (true)
                {
                    tempSw.Restart();
                    Thread.Sleep(20);//0.5秒刷新一下界面
                    #region 界面设置
                    this.Invoke(new Action(() =>
                    {
                        if (GlobalVar.isAutoRun)
                        {
                            if (GlobalVar.isPause)
                                btn_start.Text = "开始";
                            else
                                btn_start.Text = "暂停";
                            tssl_machineStatus_status.Text = "运行中";
                            tssl_machineStatus_status.BackColor = System.Drawing.Color.Green;
                        }
                        else
                        {
                            btn_start.Text = "开始";
                            tssl_machineStatus_status.Text = "未开始";
                            tssl_machineStatus_status.BackColor = System.Drawing.Color.Yellow;
                        }
                        if (GlobalVar.isEstop)
                        {
                            btn_AburptStop.Text = "急停取消";
                        }
                        else
                            btn_AburptStop.Text = "急停";
                        if (GlobalVar.IsEndWork)
                            btn_FinishWork.Text = "继续作业";
                        else
                            btn_FinishWork.Text = "结束作业";
                        tsl_cardStatus.Text = MotionControl.GlobalVariable.isCardStart[0] ? "已连接" : "未连接";
                        tsl_cardStatus.BackColor = MotionControl.GlobalVariable.isCardStart[0] ? Color.Green : Color.Red;
                        tssl_ProductType.Text = GlobalVar.closeSave.CurrentTypeName;
                      
                        nud_nfly1.Value = GlobalVar.closeSave.curFly1Count;
                        nud_nfly2.Value = GlobalVar.closeSave.curFly2Count;
                      
                    }));
                    #endregion

                    if (GlobalVar.isExit)
                    {
                        break;
                    }
                    //MessageDisplay("界面更新线程运动时间是：" + tempSw.ElapsedMilliseconds.ToString());//不加延时，此方法运行时间0-15ms
                }
            }
            catch (System.Exception ex)
            {
                Log4Helper.WriteLog("MainForm", ex);
            }


        }
      

        private void closeSoftware()
        {
            try
            {
                var forms = Application.OpenForms;
                foreach (var curForm in forms)
                {
                    if (((Form)curForm).Name == "FormAlarm" || ((Form)curForm).Name == "FormDeviceError")
                    {
                        ((Form)curForm).WindowState = FormWindowState.Minimized;
                    }
                }
                DialogResult exit = MessageBox.Show("确定退出系统吗？", "退出系统", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (exit != DialogResult.Yes)
                {
                    return;

                }
                GlobalMotion.LightState(e_LightState.全灭);
                displalyInfo.displayInfoMain($"已关蜂鸣器");
            
                GlobalVar.isExit = true;
                Thread.Sleep(100);
                GlobalMotion.Card_1.setOut((ushort)e_output_card1.上层向上游要料, e_out_OnOff.on);
                GlobalMotion.Card_1.setOut((ushort)e_output_card1.下层要料, e_out_OnOff.on);
                displalyInfo.displayInfoMain($"已保存配置");
                
                SerializeHelper.serializeFile(GlobalVar.closeSavePath, GlobalVar.closeSave, "已保存closeSave配置");
                displalyInfo.displayInfoMain($"已保存closeSave配置");
                //关灯
                if (GlobalVar.cameraList != null && GlobalVar.cameraList.Count > 0)
                {
                    for (int i = 0; i < GlobalVar.cameraList.Count; i++)
                    {
                        if (GlobalVar.cameraList[i].isInitSuccess)
                        {
                            GlobalVar.cameraList[i].stopGrab();
                            GlobalVar.cameraList[i].DisConnectDev();
                        }
                    }
                    displalyInfo.displayInfoMain($"已关闭相机");
                }
              
                this.Close();
                Process.GetCurrentProcess().Kill();
                Application.Exit();
             
            }
            catch (Exception ex)
            {
                MessageDisplay($"关闭软件出错：{ex}");

            }
        }

        private void btn_exit_Click(object sender, EventArgs e)
        {
            closeSoftware();          
        }

        /// <summary>
        /// 窗口索引
        /// </summary>
        private enum winIndex
        {
            DataDisplay=0,
            type,
            motion,
            IOcheck,
            calibation,
            communication,
            userManage
        }
        public enum e_Win
        {
            设备IO,
            程序配方,
            设备点动,
            设备状态,
            设备历史,
            控制卡设置,
            用户管理
        }
      
       
        bool IsFirstStart = true;
        private void btn_start_Click(object sender, EventArgs e)
        {
            displalyInfo.displayInfoMain(((Button)sender).Text + "按下");
        
            if (!GlobalVar.isAutoRun)
            {
                if (!IsOpenReset)
                {
                    displalyInfo.displayInfoMain("开机请先复位");
                    GlobalMotion.warnningTips(e_warningType.motor, "开机请先复位");
                    return;
                }
                if (!GlobalVar.isAllHome&&!GlobalVar.IsManThrought)
                {
                    displalyInfo.displayInfoMain("请先回原");
                    GlobalMotion.warnningTips(e_warningType.motor, "所有轴先回原才能自动运行");
                    return;
                }
                if (IsFirstStart)
                {
                  
                    GlobalVar.curStatus = e_Status.未知;
                    IsFirstStart = false;
                    GlobalVar.isFlying1OK = true;
                    GlobalVar.isFlying2OK = true;
                    GlobalMotion.Step_ConveryUp(e_Step_ConveryUp.入料段治具阻挡, e_MachineStatus.无控制);
                    GlobalMotion.Step_ConveryUp(e_Step_ConveryUp.一段治具阻挡, e_MachineStatus.无控制);
                    GlobalMotion.Step_ConveryUp(e_Step_ConveryUp.二段治具阻挡, e_MachineStatus.无控制);
                    GlobalMotion.e_ConveryFront = e_Flow_ConveryUp.等待入料治具到位;
                    GlobalMotion.e_ConveryLabel = e_Flow_ConveryUp.等待二段治具到位;
                    GlobalMotion.e_ConveryLaser = e_Flow_ConveryUp.等待一段治具到位;
                    GlobalMotion.e_ConveryOver = e_Flow_ConveryUp.等待一段治具到位;
                    GlobalMotion.e_ConveryMan = e_Flow_ConveryUp.等待人工站到达;
                    GlobalMotion.e_Cut = e_Flow_Cut.等待有工装到达;
                    GlobalMotion.e_LabelingFlow = e_Flow_Labeling.取标签;
                    GlobalMotion.fly1 = e_Flow_Fly.等待触发飞达;
                    GlobalMotion.fly2 = e_Flow_Fly.等待触发飞达;
                    GlobalVar.IsProccessed1 = false;
                    GlobalVar.IsProccessed2 = false;
                    GlobalVar.Label_Start = false;
                    GlobalVar.LabelFinshed = false;
                    GlobalVar.Cut_Finish = true;
                    GlobalVar.Cut_Start = false;
                    GlobalVar.ScanFinished = false;
                    GlobalVar.e_Camera_Pos1 = e_Camera_Pos.未拍照;
                    GlobalVar.e_Camera_Pos2 = e_Camera_Pos.未拍照;
                    GlobalVar.e_Camera_Check1 = e_Camera_Pos.未拍照;
                    GlobalVar.e_Camera_Check2 = e_Camera_Pos.未拍照;
                    GlobalVar.IsPosBeforeLabel = false;
                    GlobalVar.front_pros = new List<ProductInfo>();
                    GlobalVar.Laser_pros = new List<ProductInfo>();
                    GlobalVar.Label_pros = new List<ProductInfo>();
                    displalyInfo.displayInfoMain("回零后首次开机");
                }
                this.Invoke(new Action(()=> {
                    btn_Home.Enabled = false;
                    btn_AburptStop.Enabled = true;
                    btn_FinishWork.Enabled = true;
                    pl_main.Enabled = false;
                    rbx_displayMessage.Focus();
                }));
                GlobalVar.IsEndWork = false;
                GlobalVar.isAutoRun = true;
                GlobalVar.isPause = false;//要在isAutoRun后
            }else
            {
                if (GlobalVar.isPause)
                {
                    GlobalVar.curStatus = e_Status.未知;
                    GlobalVar.isPause = false;
                   
                }
                else
                {
                    GlobalVar.isPause = true;
                    GlobalVar.curStatus = e_Status.暂停中;
                }
                this.Invoke(new Action(() => {
                    pl_main.Enabled = true;
                    rbx_displayMessage.Focus();
                }));
            }
            GlobalVar.IsMesEstop = false;
        }

      
        private void Operate_GiveUp()
        {
            displalyInfo.displayInfoMain("放弃操作");
            runTimeSW.Stop();
            LastTimeSW.Stop();
            //GlobalMotion.mainCard.AxisList[7].AxisStop();
            MotionControl.GlobalVariable.HOperation.AllAxisStop(GlobalMotion.Card_1.m_CardID);
            GlobalVar.isAutoRun = false;
            if (InvokeRequired)
            {
                this.Invoke(new Action(() =>
                {
                    btn_start.Enabled = true;
                    btn_FinishWork.Enabled = false;
                    btn_Home.Enabled = true;
                }));
            }
            else
            {
                btn_start.Enabled = true;
                btn_FinishWork.Enabled = false;
                btn_Home.Enabled = true;
            }
            //MotionControl.GlobalVariable.HOperation.SetOut(GlobalMotion.mainCard.m_CardID, (ushort)11, 1);//绿灯灭
            //Interlocked.Exchange(ref GlobalVar.stepNo ,4);//操作步设置为0
        }
        private void btn_Stop_Click(object sender, EventArgs e)
        {
            GlobalVar.IsEndWork = true;
        }

        private void btn_GiveUp_Click(object sender, EventArgs e)
        {
            Operate_GiveUp();
        }
        public void Estop()
        {
            runTimeSW.Stop();
            LastTimeSW.Stop();
            if (GlobalVar.isEstop)
            {
                GlobalVar.isEstop = false;
                this.Invoke(new Action(()=> {
                    btn_Home.Enabled = true;
                }) );
                displalyInfo.displayInfoMain("软件急停取消");
            }
            else
            {
                MotionControl.GlobalVariable.HOperation.AllAxisStop(GlobalMotion.Card_1.m_CardID);
                btn_start.Enabled = true;
                GlobalVar.errorTips[(int)e_errorType.softEstop].haveInfo = true;
                GlobalVar.isEstop = true;
                GlobalVar.isAutoRun = false;
                GlobalVar.isAllHome = false;
                GlobalVar.isPause = true;
                GlobalMotion.MachineState(e_MachineStatus.异常急停, "触发软急停");
                this.Invoke(new Action(() => {
              
                    pl_main.Enabled = true;
                }));
                GlobalVar.IsMesEstop = false;
                displalyInfo.displayInfoMain("软件急停");
            }
        }
        private void btn_AburptStop_Click(object sender, EventArgs e)
        {
         
             Estop();
            if (!IsOpenReset)
            {
                if (GlobalVar.isEstop)
                    GlobalVar.curStatus = e_Status.停止中;
                else
                {
                    if (GlobalVar.curStatus == e_Status.停止中)
                        GlobalVar.curStatus = e_Status.未知;
                }
            }else
            {
                if(GlobalVar.isEstop)
                    GlobalVar.curStatus = e_Status.停止中;
                else
                {
                    if(GlobalVar.curStatus==e_Status.停止中)
                        GlobalVar.curStatus = e_Status.未知;
                }
            }
            GlobalVar.IsMesEstop = false;
        }

        private void btn_type_Click(object sender, EventArgs e)
        {
            ShowPage("其他");
            foreach (var curControl in tableLayoutPanel2.Controls)
            {
                if(curControl is Button)
                {
                    ((Button)curControl).BackColor = Color.Gray;
                }
            }
            ((Button)sender).BackColor = Color.Orange;
            var arr = Enum.GetNames(typeof( e_Win));
            if (arr.Contains(((Button)sender).Tag.ToString()))
            {
                var curWin = (e_Win)Enum.Parse(typeof(e_Win), ((Button)sender).Tag.ToString());
                showHideWin(curWin);
       
                displalyInfo.displayInfoMain($"进入{curWin.ToString()}模块");
            }
        }
        bool isAirAll = true;

        private void btn_Home_Click(object sender, EventArgs e)
        {
            if(GlobalVar.isEstop)
            {
                MessageBox.Show("急停中不能复位！");
                return;
            }
            isAirAll = true;
            var forms = Application.OpenForms;
            foreach (var curForm in forms)
            {
                if (((Form)curForm).Name == "FormAlarm" || ((Form)curForm).Name == "FormDeviceError")
                {
                    ((Form)curForm).WindowState = FormWindowState.Minimized;
                }
            }
            if(!GlobalVar.isPause&& GlobalVar.isAutoRun)
            {
                MessageBox.Show("先停止自动运行再复位！");
                return ;
            }
            if (!GlobalVar.IsTcpReset )
            {
                if (MessageBox.Show("所有轴将进行回零,确认要复位吗？", "询问", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                {
                    btn_Home.Enabled = true;
                    return;
                }
            }
            btn_start.Enabled = false;
            GlobalVar.IsTcpReset = false;
            GlobalVar.isReseting = true;
            GlobalVar.isPause = false;
            IsOpenReset = true;
            GlobalVar.isAutoRun = false;
            Thread.Sleep(100);
            IsFirstStart = true;
            GlobalVar.IsMesEstop = false;
            var nres = GlobalMotion.home_all_continue();
            GlobalVar.isReseting = false;
            if (nres == 1)
            {
                GlobalVar.curStatus = e_Status.设备复位完成;
                displalyInfo.displayInfoMain("所有轴回零完成！");
                MessageBox.Show("所有轴回零完成！");
            }
            else
            {
                GlobalVar.curStatus = e_Status.设备未复位;
                GlobalVar.isEstop = true;////临时
                displalyInfo.displayErrorMain("所有轴回零失败！");
                MessageBox.Show("所有轴回零失败！");
            }
            btn_start.Enabled = true;
            //Operate_Home();
        }
        private void ClearErrorStatus()
        {
            try
            {
                GlobalVar.isEstop = false;
                for (int i = 0; i < GlobalVar.errorTips.Length; i++)
                {
                    GlobalVar.errorTips[i].haveInfo = false;
                    GlobalVar.errorTips[i].Info = string.Empty;
                }
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain("清除错误状态异常："+ex.Message);
            }
        }
        private bool TcpReset = false;






        public void ImageDisplay_2(HObject measureImage)
        {
            try
            {
               
                    hswc_Scan.BeginInvoke(new MethodInvoker(() =>
                    {

                        hswc_Scan.HalconWindow.ClearWindow();

                        measureImage.DispObj(hswc_Scan.HalconWindow);
                       
                        hswc_Scan.SetFullImagePart();
                    }));
                
               
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain("外形检测显示异常:" + ex.Message);
                Log4Helper.WriteLog(ex);
            }
        }
        public void ImageDisplay_2_obj(HObject measureImage, string color)
        {
            try
            {
                if (InvokeRequired)
                {
                    hswc_Scan.BeginInvoke(new MethodInvoker(() =>
                    {
                        //hswc_measure.HalconWindow.ClearWindow();
                        //hswc_measure.HalconWindow.SetDraw("margin");
                        hswc_Scan.HalconWindow.SetColor(color);
                        measureImage.DispObj(hswc_Scan.HalconWindow);
                        hswc_Scan.SetFullImagePart();
                    }));
                }
                else
                {
                    //hswc_measure.HalconWindow.ClearWindow();
                    //hswc_measure.HalconWindow.SetDraw("margin");
                    hswc_Scan.HalconWindow.SetColor(color);
                    measureImage.DispObj(hswc_Scan.HalconWindow);
                    hswc_Scan.SetFullImagePart();
                }
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain("图案检测显示异常:" + ex.Message);
                Log4Helper.WriteLog(ex);
            }
        }
        private void hswc_cam_1_Load(object sender, EventArgs e)
        {
            hswc_Scan.Parent.MouseWheel += my_MouseWheel_1;
            GlobalVar.hwindow_cam_1_hwin = hswc_Scan.HalconWindow;
            hswc_Scan.HMouseMove += new HMouseEventHandler(Image_MouseMove);
            hswc_Scan.HMouseDown += new HMouseEventHandler(Image_MouseDown);
            hswc_Scan.HMouseUp += new HMouseEventHandler(Image_MouseUp);
            hswc_Scan.HalconWindow.SetDraw("margin");
            hswc_Scan.SetFullImagePart();
        }
        private void hswc_cam_1_HMouseMove(object sender, HMouseEventArgs e)
        {
            try
            {
                if (!is_hsmc_1_grayValue_display || e.X <= 0 || e.Y <= 0 ||
                    GlobalVar.Cam_1_hobj == null)
                {
                    return;
                }
                HTuple grayval, width, height;
                HOperatorSet.GetImageSize(GlobalVar.Cam_1_hobj, out width, out height);
                if (e.X >= 0 && e.X < width && e.Y >= 0 && e.Y < height)
                {
                    HOperatorSet.GetGrayval(GlobalVar.Cam_1_hobj, e.Y, e.X, out grayval);
                 
                }
            }
            catch (System.Exception ex)
            {
                Log4Helper.WriteLog(ex);
                displalyInfo.displayInfoMain("灰度值显示异常：" + ex.Message);
            }
        }
        private void my_MouseWheel_1(object sender, MouseEventArgs e)
        {
            try
            {


                Point pt = hswc_Scan.Location;

                int leftBorder = hswc_Scan.Location.X;
                int rightBorder = hswc_Scan.Location.X + hswc_Scan.Size.Width;
                int topBorder = hswc_Scan.Location.Y;
                int bottomBorder = hswc_Scan.Location.Y + hswc_Scan.Size.Height;

                if (e.X > leftBorder && e.X < rightBorder && e.Y > topBorder && e.Y < bottomBorder)
                {
                    MouseEventArgs newe = new MouseEventArgs(e.Button, e.Clicks, e.X - pt.X, e.Y - pt.Y, e.Delta);
                    hswc_Scan.HSmartWindowControl_MouseWheel(sender, newe);
                }

            }
            catch (System.Exception ex)
            {
                displalyInfo.displayInfoMain("鼠标滚轮操作异常 :" + ex.Message);
                Log4Helper.WriteLog(ex);
            }

        }
        private void my_MouseWheel_3(object sender, MouseEventArgs e)
        {
            try
            {


                Point pt = hswc_Check.Location;

                int leftBorder = hswc_Check.Location.X;
                int rightBorder = hswc_Check.Location.X + hswc_Check.Size.Width;
                int topBorder = hswc_Check.Location.Y;
                int bottomBorder = hswc_Check.Location.Y + hswc_Check.Size.Height;

                if (e.X > leftBorder && e.X < rightBorder && e.Y > topBorder && e.Y < bottomBorder)
                {
                    MouseEventArgs newe = new MouseEventArgs(e.Button, e.Clicks, e.X - pt.X, e.Y - pt.Y, e.Delta);
                    hswc_Check.HSmartWindowControl_MouseWheel(sender, newe);
                }

            }
            catch (System.Exception ex)
            {
                displalyInfo.displayInfoMain("鼠标滚轮操作异常 :" + ex.Message);
                Log4Helper.WriteLog(ex);
            }

        }

        public void ImageDisplay_1(HObject measureImage)
        {
            try
            {
                
                if (InvokeRequired)
                {
                    hswc_Postion.BeginInvoke(new MethodInvoker(() =>
                    {

                        hswc_Postion.HalconWindow.ClearWindow();
                        measureImage.DispObj(hswc_Postion.HalconWindow);
                        hswc_Postion.SetFullImagePart();
                    }));
                }
                else
                {
                
                    hswc_Postion.HalconWindow.ClearWindow();
                    measureImage.DispObj(hswc_Postion.HalconWindow);
                    hswc_Postion.SetFullImagePart();
                }
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain("外形检测显示异常:" + ex.Message);
                Log4Helper.WriteLog(ex);
            }
        }
        public void ImageDisplay_1_obj(HObject measureImage, string color)
        {
            if (measureImage == null)
                measureImage = new HObject();
            //if (InvokeRequired)
            //{
            hswc_Postion.BeginInvoke(new MethodInvoker(() =>
            {
                try
                {
                    //hswc_measure.HalconWindow.ClearWindow();
                    hswc_Postion.HalconWindow.SetDraw("margin");
                    hswc_Postion.HalconWindow.SetColor(color);
                    measureImage.DispObj(hswc_Postion.HalconWindow);
                    hswc_Postion.SetFullImagePart();
                }
                catch (Exception ex)
                {
                    displalyInfo.displayInfoMain("定位相机显示异常:" + ex.Message);
                    Log4Helper.WriteLog(ex);
                }
            }));
         
        }
        public void ImageDisplay_3(HObject measureImage)
        {
            try
            {

                if (InvokeRequired)
                {
                    hswc_Check.BeginInvoke(new MethodInvoker(() =>
                    {
                        hswc_Check.HalconWindow.ClearWindow();
                        measureImage.DispObj(hswc_Check.HalconWindow);
                        hswc_Check.SetFullImagePart();
                    }));
                }
                else
                {
                    hswc_Check.HalconWindow.ClearWindow();
                    measureImage.DispObj(hswc_Check.HalconWindow);
                    hswc_Check.SetFullImagePart();
                }
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain("外形检测显示异常:" + ex.Message);
                Log4Helper.WriteLog(ex);
            }
        }
        public void ImageDisplay_3_obj(HObject measureImage, string color)
        {
            try
            {
                if (measureImage == null)
                    measureImage = new HObject();
                if (InvokeRequired)
                {
                    hswc_Check.BeginInvoke(new MethodInvoker(() =>
                    {
                        hswc_Check.HalconWindow.SetDraw("margin");
                        hswc_Check.HalconWindow.SetColor(color);
                        measureImage.DispObj(hswc_Check.HalconWindow);
                        hswc_Check.SetFullImagePart();
                    }));
                }
                else
                {
                    hswc_Check.HalconWindow.SetDraw("margin");
                    hswc_Check.HalconWindow.SetColor(color);
                    measureImage.DispObj(hswc_Check.HalconWindow);
                    hswc_Check.SetFullImagePart();
                }
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain("检测相机显示异常:" + ex.Message);
                Log4Helper.WriteLog(ex);
            }
        }
        public void ImageDisplay_1_objSimple(HObject drawObject, string color)
        {
            try
            {
                if (InvokeRequired)
                {
                    hswc_Postion.Invoke(new MethodInvoker(() =>
                    {
                        hswc_Postion.HalconWindow.ClearWindow();
                        hswc_Postion.HalconWindow.DispObj(visionProc.srcObject_pos);
                        hswc_Postion.HalconWindow.SetColor(color);
                        hswc_Postion.HalconWindow.SetDraw("margin");
                        hswc_Postion.HalconWindow.DispObj(drawObject);
                        
                    }));
                }
                else
                {
                    hswc_Postion.HalconWindow.ClearWindow();
                    hswc_Postion.HalconWindow.DispObj(visionProc.srcObject_pos);
                    hswc_Postion.HalconWindow.SetColor(color);
                    hswc_Postion.HalconWindow.SetDraw("margin");
                    hswc_Postion.HalconWindow.DispObj(drawObject);
                   
                }
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain("定位相机检测显示异常:" + ex.Message);
                Log4Helper.WriteLog(ex);
            }
        }
        public void ImageDisplay_2_objSimple(HObject drawObject, string color)
        {
            try
            {
                if (InvokeRequired)
                {
                    hswc_Scan.Invoke(new MethodInvoker(() =>
                    {
                        hswc_Scan.HalconWindow.ClearWindow();
                        hswc_Scan.HalconWindow.DispObj(visionProc.srcObject_scan);
                        hswc_Scan.HalconWindow.SetColor(color);
                        hswc_Scan.HalconWindow.SetDraw("margin");
                        hswc_Scan.HalconWindow.DispObj(drawObject);

                    }));
                }
                else
                {
                    hswc_Scan.HalconWindow.ClearWindow();
                    hswc_Scan.HalconWindow.DispObj(visionProc.srcObject_scan);
                    hswc_Scan.HalconWindow.SetColor(color);
                    hswc_Scan.HalconWindow.SetDraw("margin");
                    hswc_Scan.HalconWindow.DispObj(drawObject);

                }
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain("检测显示异常2:" + ex.Message);
                Log4Helper.WriteLog(ex);
            }
        }

        private void Image_MouseDown(object sender, HMouseEventArgs e)
        {
            if (!isDown1 && e.Button.ToString() == "Left" && visionProc.isReduce)
            {
                hswc_Postion.HMoveContent = false;
                hswc_Scan.HMoveContent = false;
                //   this.MouseWheel -= my_MouseWheel_2;
                isDown1 = true;
            }
        }
        private void Image_MouseUp(object sender, HMouseEventArgs e)
        {
            if (isDown1)
            {
                isDown1 = false;
                hswc_Postion.HMoveContent = true;
                hswc_Scan.HMoveContent = true;
                // this.MouseWheel += my_MouseWheel_2;
            }
        }
        private void hswc_cam_2_Load(object sender, EventArgs e)
        {
            hswc_Postion.Parent.MouseWheel += my_MouseWheel_2;
            
            hswc_Postion.HMouseMove += new HMouseEventHandler(Image_MouseMove);
            hswc_Postion.HMouseDown += new HMouseEventHandler(Image_MouseDown);
            hswc_Postion.HMouseUp += new HMouseEventHandler(Image_MouseUp);
            GlobalVar.hwindow_cam_2_hwin = hswc_Postion.HalconWindow;
            hswc_Postion.HalconWindow.SetDraw("margin");
            hswc_Postion.SetFullImagePart();
        }
        bool isDown1 = false;
        PointF point_move;
        /// <summary>
        /// 涂抹区域
        /// </summary>
        HObject MaskRegion1 = new HObject();
        /// <summary>
        /// 涂抹区域
        /// </summary>
        HObject MaskRegion2 = new HObject();
        /// <summary>
        /// 鼠标移动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Image_MouseMove(object sender, HMouseEventArgs e)
        {

            if (((HSmartWindowControl)sender).Name == "hswc_Postion")
            {
                tbx_pixX.Text = e.X.ToString();
                tbx_pixY.Text = e.Y.ToString();
                if (e.Button.ToString() == "Left" && e.Y > 0 && e.X > 0)
                {
                    HOperatorSet.GetImageSize(visionProc.srcObject_pos, out HTuple imgWidth, out HTuple imgHeight);
                    if (e.X <= imgWidth.D && e.Y <= imgHeight.D)
                    {
                        HOperatorSet.GetGrayval(visionProc.srcObject_pos, e.Y, e.X, out HTuple grayval);
                        tbx_grayVal.Text = grayval.I.ToString();
                    }
                }
                if (isDown1 && e.Button.ToString() == "Left" && visionProc.isReduce)
                {
                    point_move = new PointF((float)e.X, (float)e.Y);
                    HObject curRegion;
                    HOperatorSet.GenCircle(out curRegion, point_move.Y, point_move.X, visionProc.reduce_Radius);
                    if (!MaskRegion1.IsInitialized())
                        MaskRegion1 = curRegion;
                    else
                    {
                        HObject conObj;
                        HOperatorSet.ConcatObj(MaskRegion1, curRegion, out conObj);
                        MaskRegion1 = conObj;
                    }
                    HOperatorSet.Difference(visionProc.ROI1.ROI_Template, MaskRegion1, out HObject MaskResult);
                    visionProc.ROI1.ROI_Template = MaskResult;
                    ImageDisplay_1_objSimple(visionProc.ROI1.ROI_Template, "blue");
                }
            }
            if (((HSmartWindowControl)sender).Name == "hswc_Scan")
            {
                tbx_s_X.Text = e.X.ToString();
                tbx_s_Y.Text = e.Y.ToString();
                if (e.Button.ToString() == "Left" && e.Y > 0 && e.X > 0)
                {
                    HOperatorSet.GetImageSize(visionProc.srcObject_scan, out HTuple imgWidth, out HTuple imgHeight);
                    if (e.X <= imgWidth.D && e.Y <= imgHeight.D)
                    {
                        HOperatorSet.GetGrayval(visionProc.srcObject_scan, e.Y, e.X, out HTuple grayval);
                        tbx_s_grayVal.Text = grayval.I.ToString();
                    }
                }
                if (isDown1 && e.Button.ToString() == "Left" && visionProc.isReduce)
                {
                    point_move = new PointF((float)e.X, (float)e.Y);
                    HObject curRegion;
                    HOperatorSet.GenCircle(out curRegion, point_move.Y, point_move.X, visionProc.reduce_Radius);
                    if (!MaskRegion2.IsInitialized())
                        MaskRegion2 = curRegion;
                    else
                    {
                        HObject conObj;
                        HOperatorSet.ConcatObj(MaskRegion2, curRegion, out conObj);
                        MaskRegion2 = conObj;
                    }
                    HOperatorSet.Difference(visionProc.ROI2.ROI_Template, MaskRegion2, out HObject MaskResult);
                    visionProc.ROI2.ROI_Template = MaskResult;
                    ImageDisplay_2_objSimple(visionProc.ROI2.ROI_Template, "blue");
                }
            }
            if (((HSmartWindowControl)sender).Name == "hswc_Check")
            {
               
                if (visionProc.srcObject_ckeck!=null && e.Y > 0 && e.X > 0)
                {
                    HOperatorSet.GetImageSize(visionProc.srcObject_ckeck, out HTuple imgWidth, out HTuple imgHeight);
                    if (e.X <= imgWidth.D && e.Y <= imgHeight.D)
                    {
                        HOperatorSet.GetGrayval(visionProc.srcObject_ckeck, e.Y, e.X, out HTuple grayval);
                        tbx_grayVal3.Text = grayval.I.ToString();
                    }
                }
                
            }
        }
        private void hswc_cam_2_HMouseMove(object sender, HMouseEventArgs e)
        {
            try
            {
                if (!is_hsmc_2_grayValue_display || e.X <= 0 || e.Y <= 0 ||
                    GlobalVar.Cam_2_hobj == null)
                {
                    return;
                }
                HTuple grayval, width, height;
                HOperatorSet.GetImageSize(GlobalVar.Cam_2_hobj, out width, out height);
                if (e.X >= 0 && e.X < width && e.Y >= 0 && e.Y < height)
                {
                    HOperatorSet.GetGrayval(GlobalVar.Cam_2_hobj, e.Y, e.X, out grayval);
                    lbl_grayValue_2.Text = $"row :{(e.Y).ToString("#0.0")} , column :{(e.X).ToString("#0.0")} , value :{grayval}";
                }
            }
            catch (System.Exception ex)
            {
                Log4Helper.WriteLog(ex);
                displalyInfo.displayInfoMain("灰度值显示异常：" + ex.Message);
            }
        }
        private void my_MouseWheel_2(object sender, MouseEventArgs e)
        {
            try
            {


                Point pt = hswc_Postion.Location;

                int leftBorder = hswc_Postion.Location.X;
                int rightBorder = hswc_Postion.Location.X + hswc_Postion.Size.Width;
                int topBorder = hswc_Postion.Location.Y;
                int bottomBorder = hswc_Postion.Location.Y + hswc_Postion.Size.Height;

                if (e.X > leftBorder && e.X < rightBorder && e.Y > topBorder && e.Y < bottomBorder)
                {
                    MouseEventArgs newe = new MouseEventArgs(e.Button, e.Clicks, e.X - pt.X, e.Y - pt.Y, e.Delta);
                    hswc_Postion.HSmartWindowControl_MouseWheel(sender, newe);
                }

            }
            catch (System.Exception ex)
            {
                displalyInfo.displayInfoMain("鼠标滚轮操作异常 :" + ex.Message);
                Log4Helper.WriteLog(ex);
            }

        }
     
        private List<HDrawingObject> draw_up_region_template;
        public void DrawRoiRegion1()
        {
            visionProc.DrawRoiRegion1(hswc_Postion);
        }

      
        public void ClearRoiRegion1()
        {
            visionProc.ClearROIRegion1();
        }
        public void DrawRoiRegion2()
        {
            visionProc.DrawRoiRegion2(hswc_Scan);
        }
        public void ClearRoiRegion2()
        {
            visionProc.ClearROIRegion2();
        }
        public void DrawRoiRegion3()
        {
            visionProc.DrawRoiRegion3(hswc_Check);
        }
        public void ClearRoiRegion3()
        {
            visionProc.ClearROIRegion3();
        }



        private void toolStripStatusLabel1_Click(object sender, EventArgs e)
        {

        }

        private void btn_addFront_Click(object sender, EventArgs e)
        {
           
        }

        private void button2_Click(object sender, EventArgs e)
        {
            GlobalVar.Cut_Finish = true;
        }

        private void btn_lableFinished_Click(object sender, EventArgs e)
        {
            GlobalVar.LabelFinshed = true;
        }

        private void btn_flystart1_Click(object sender, EventArgs e)
        {
            GlobalVar.IsflyStart1 = true;
        }

        private void btn_flystart2_Click(object sender, EventArgs e)
        {
            GlobalVar.IsflyStart2 = true;
        }

        private void btn_labelStart_Click(object sender, EventArgs e)
        {
            GlobalVar.Label_Start = true;
        }

        private void btn_cameraProccessNG_Click(object sender, EventArgs e)
        {
            GlobalVar.e_Camera_Pos1 = e_Camera_Pos.已拍照NG;
            GlobalVar.IsProccessed1 = true;
            
        }

        private void button3_Click(object sender, EventArgs e)
        {
            GlobalVar.e_Camera_Pos2 = e_Camera_Pos.已拍照NG;
            GlobalVar.IsProccessed2 = true;
        }

        private void btn_cameraProccessOK_Click(object sender, EventArgs e)
        {
            GlobalVar.e_Camera_Pos1 = e_Camera_Pos.已拍照OK;
            GlobalVar.IsProccessed1 = true;
        }

        private void btn_cameraProccessOK2_Click(object sender, EventArgs e)
        {
            GlobalVar.e_Camera_Pos2 = e_Camera_Pos.已拍照OK;
            GlobalVar.IsProccessed2 = true;
        }

        private void btn_checkNG1_Click(object sender, EventArgs e)
        {
            GlobalVar.e_Camera_Check1 = e_Camera_Pos.已拍照NG;
        }

        private void btn_checkNG2_Click(object sender, EventArgs e)
        {
            GlobalVar.e_Camera_Check2 = e_Camera_Pos.已拍照NG;
        }

        private void btn_LaserStart_Click(object sender, EventArgs e)
        {
            GlobalVar.Cut_Start = true;
        }
        private void btn_laserFinished_Click(object sender, EventArgs e)
        {
            GlobalVar.Cut_Finish = true;
        }

        private void btn_checkOK1_Click(object sender, EventArgs e)
        {
            GlobalVar.e_Camera_Check1 = e_Camera_Pos.已拍照OK;
        }

        private void btn_checkOK2_Click(object sender, EventArgs e)
        {
            GlobalVar.e_Camera_Check2 = e_Camera_Pos.已拍照OK;
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void btn_mainPage_Click(object sender, EventArgs e)
        {
            foreach (var curControl in tableLayoutPanel2.Controls)
            {
                if (curControl is Button)
                {
                    ((Button)curControl).BackColor = Color.Gray;
                }
            }
             ((Button)sender).BackColor = Color.Orange;
            ShowPage("主页");
        }
        private string curStr = "";
        private void ShowPage(string page)
        {
            var tempStr = page;
            if (curStr== page)
            {
                tempStr = "不用切换";
            }
            curStr = page;
            switch (tempStr)
            {
                case "主页":
                    foreach (var ctr in panel3.Controls)
                    {
                        ((Control)ctr).Hide();
                    }
                    MainPage.Show();
                    break;
                case "其他":
                    foreach (var ctr in panel3.Controls)
                    {
                        ((Control)ctr).Hide();
                    }
                    pl_main.Show();
                    tabControl1.Show();
                    panel4.Show();
                  
                    break;
            }
        }

        private void hswc_Check_Load(object sender, EventArgs e)
        {
            hswc_Check.Parent.MouseWheel += my_MouseWheel_3;
            hswc_Check.HMouseMove += new HMouseEventHandler(Image_MouseMove);
            hswc_Check.HalconWindow.SetDraw("margin");
            hswc_Check.SetFullImagePart();
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            GlobalVar.IsOldTest = checkBox1.Checked;
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            GlobalVar.IsAutoAddData = checkBox2.Checked;
        }

        private void btn_softTriger1_Click(object sender, EventArgs e)
        {
            try
            {
                GlobalVar.cameraList[(int)e_Camera.定位相机].softTrigger();
            }
            catch(Exception ex)
            {
                displalyInfo.displayInfoMain(ex.Message);
            }
        }

        private void btn_softTriger2_Click(object sender, EventArgs e)
        {
            try
            {
                GlobalVar.cameraList[(int)e_Camera.图案相机].softTrigger();
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain(ex.Message);
            }
        }

        private void btn_softTriger3_Click(object sender, EventArgs e)
        {
            try
            {
                GlobalVar.cameraList[(int)e_Camera.检测相机].softTrigger();
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain(ex.Message);
            }
        }

        private void btn_downPro_Click(object sender, EventArgs e)
        {
           
        }

        private void ckb_Down_CheckedChanged(object sender, EventArgs e)
        {
            GlobalVar.IsMaunalDown = ckb_Down.Checked;
        }

        private void btn_DownRealse_Click(object sender, EventArgs e)
        {
           
            GlobalMotion.ConveryControrl(e_ConveryControl.下层治具放行, e_MachineStatus.无控制);//放行
        }

        private void btn_Down_Click(object sender, EventArgs e)
        {
           
            GlobalMotion.ConveryControrl(e_ConveryControl.下层治具阻挡, e_MachineStatus.无控制);//放行
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (GlobalMotion.Card_1.AxisList[(int)e_card1_axis.下层输送左].m_AxisSts.Motion)
                GlobalMotion.ConveryControrl(e_ConveryControl.下层输送停止, e_MachineStatus.无控制);
            else
                GlobalMotion.ConveryControrl(e_ConveryControl.下层输送启动, e_MachineStatus.无控制);
        }

        private void btn_downHave_Click(object sender, EventArgs e)
        {

        }

        private void button4_Click(object sender, EventArgs e)
        {

        }

        private void ckb_downPro_CheckedChanged(object sender, EventArgs e)
        {
            GlobalVar.IsRealsePro = ckb_downPro.Checked;
        }

        private void btn_ResetCut_Click(object sender, EventArgs e)
        {
            if (!GlobalMotion.Input_CardEx2[(int)e_input_extCard2.上输送治具检测2] && GlobalVar.isAutoRun)
            {
                var msg = "撕膜工位无治具,操作无效";
                MessageBox.Show(msg);
                return;
            }
            if (GlobalVar.Laser_pros == null || GlobalVar.Laser_pros.Count == 0)
            {
                GlobalVar.Laser_pros = new List<ProductInfo>();
                GlobalVar.Laser_pros.Add(new ProductInfo()
                {
                    LaserTime = DateTime.Now,
                    typeName = GlobalVar.closeSave.CurrentTypeName,
                    ProId = "O1",
                    ProNo = 1,
                    IsProcessAlarm=1,
                    Result_up = e_Result.进料OK.ToString()
                });
                GlobalVar.Laser_pros.Add(new ProductInfo()
                {
                    LaserTime = DateTime.Now,
                    typeName = GlobalVar.closeSave.CurrentTypeName,
                    ProId = "O1",
                    ProNo = 2,
                    IsProcessAlarm = 1,
                    Result_up = e_Result.进料OK.ToString()
                });
            }
            GlobalMotion.e_ConveryLaser = e_Flow_ConveryUp.一段治具到位;
        }

        private void btn_resetLabel_Click(object sender, EventArgs e)
        {
            if (!GlobalMotion.Input_CardEx2[(int)e_input_extCard2.上输送治具检测3] && GlobalVar.isAutoRun)
            {
                var msg = "贴标工位无治具,操作无效";
                MessageBox.Show(msg);
                return;
            }
            if (GlobalVar.Label_pros == null || GlobalVar.Label_pros.Count == 0)
            {
                GlobalVar.Label_pros = new List<ProductInfo>();
                GlobalMotion.Step_ConveryUp(e_Step_ConveryUp.二段治具升起);
                bool IshavePro3 = !GlobalMotion.Input_CardEx2[(int)e_input_extCard2.上输送产品检测3];
                bool IshavePro4 = !GlobalMotion.Input_CardEx2[(int)e_input_extCard2.上输送产品检测4];
                GlobalVar.Label_pros.Add(new ProductInfo()
                {
                    LaserTime = DateTime.Now,
                    typeName = GlobalVar.closeSave.CurrentTypeName,
                    ProId = "O1",
                    ProNo = 1,
                    IsProcessAlarm = 1,
                    Result_up = e_Result.进料OK.ToString(),
                     
                }) ;
                GlobalVar.Label_pros.Add(new ProductInfo()
                {
                    LaserTime = DateTime.Now,
                    typeName = GlobalVar.closeSave.CurrentTypeName,
                    ProId = "O1",
                    ProNo = 2,
                    IsProcessAlarm = 1,
                    Result_up = e_Result.进料OK.ToString()
                });
            }
            GlobalMotion.e_ConveryLabel = e_Flow_ConveryUp.二段治具到位;
        }

        private void btn_CutOver_Click(object sender, EventArgs e)
        {
            if (!GlobalMotion.Input_CardEx2[(int)e_input_extCard2.上输送治具检测2] && GlobalVar.isAutoRun)
            {
                var msg = "撕膜工位无治具,操作无效";
                MessageBox.Show(msg);
                return;
            }
            if (GlobalVar.Laser_pros == null || GlobalVar.Laser_pros.Count == 0)
            {
                GlobalVar.Laser_pros = new List<ProductInfo>();
                GlobalMotion.Step_ConveryUp(e_Step_ConveryUp.一段治具升起);
                bool IshavePro1 = !GlobalMotion.Input_CardEx2[(int)e_input_extCard2.上输送产品检测1];
                bool IshavePro2 = !GlobalMotion.Input_CardEx2[(int)e_input_extCard2.上输送产品检测2];
                GlobalVar.Laser_pros.Add(new ProductInfo()
                {
                    LaserTime = DateTime.Now,
                    typeName = GlobalVar.closeSave.CurrentTypeName,
                    ProId = "O1",
                    ProNo = 1,
                    IsProcessAlarm = 1,
                    Result_up = IshavePro1?e_Result.进料OK.ToString(): e_Result.进料读卡NG.ToString(),
                    Result_Cut= IshavePro1?e_Result.撕膜OK.ToString() : e_Result.撕膜NG.ToString(),
                });
                GlobalVar.Laser_pros.Add(new ProductInfo()
                {
                    LaserTime = DateTime.Now,
                    typeName = GlobalVar.closeSave.CurrentTypeName,
                    ProId = "O1",
                    ProNo = 2,
                    IsProcessAlarm = 1,
                    Result_up = IshavePro2 ? e_Result.进料OK.ToString() : e_Result.进料读卡NG.ToString(),
                    Result_Cut = IshavePro2 ? e_Result.撕膜OK.ToString() : e_Result.撕膜NG.ToString(),
                });
            }
            GlobalMotion.e_ConveryLaser = e_Flow_ConveryUp.一段治具加工完成;
        }

        private void btn_LabelOver_Click(object sender, EventArgs e)
        {
            if (!GlobalMotion.Input_CardEx2[(int)e_input_extCard2.上输送治具检测3] && GlobalVar.isAutoRun)
            {
                var msg = "贴标工位无治具,操作无效";
                MessageBox.Show(msg);
                return;
            }
            if (GlobalVar.Label_pros == null || GlobalVar.Label_pros.Count == 0)
            {
                GlobalVar.Label_pros = new List<ProductInfo>();
                GlobalMotion.Step_ConveryUp(e_Step_ConveryUp.二段治具升起);
                bool IshavePro3 = !GlobalMotion.Input_CardEx2[(int)e_input_extCard2.上输送产品检测3];
                bool IshavePro4 = !GlobalMotion.Input_CardEx2[(int)e_input_extCard2.上输送产品检测4];
                GlobalVar.Label_pros.Add(new ProductInfo()
                {
                    LaserTime = DateTime.Now,
                    typeName = GlobalVar.closeSave.CurrentTypeName,
                    ProId = "O1",
                    ProNo = 1,
                    IsProcessAlarm = 1,
                  
                    Result_up = e_Result.进料OK.ToString(),
                    Result_Label = IshavePro3 ? e_Result.贴膜OK.ToString() : e_Result.贴膜NG.ToString(),
                    Result_down = IshavePro3 ? e_Result.出料OK.ToString() : e_Result.出料NG.ToString(),
                });
                GlobalVar.Label_pros.Add(new ProductInfo()
                {
                    LaserTime = DateTime.Now,
                    typeName = GlobalVar.closeSave.CurrentTypeName,
                    ProId = "O1",
                    ProNo = 2,
                    IsProcessAlarm = 1,
                    Result_up = e_Result.进料OK.ToString(),
                    Result_Label = IshavePro4 ? e_Result.贴膜OK.ToString() : e_Result.贴膜NG.ToString(),
                    Result_down = IshavePro4 ? e_Result.出料OK.ToString() : e_Result.出料NG.ToString(),
                });
            }
           
            GlobalMotion.e_ConveryLabel = e_Flow_ConveryUp.二段治具加工完成;
        }

        private void ckb_IsSaftGate_CheckedChanged(object sender, EventArgs e)
        {
            GlobalVar.closeSave.IsSaftGate = ckb_IsSaftGate.Checked;


        }

        private async void btn_connect_Click(object sender, EventArgs e)
        {
            btn_connect.Enabled = false;
            await Task.Run(() =>
            {
                var res = GlobalMotion.Card_1.SoftReset((ushort)GlobalMotion.Card_1.m_CardID);
                if (res != -1)
                {
                    MessageBox.Show("已能正常连接运动控制卡,请重启软件生效");
                }
            });
            btn_connect.Enabled = true;
        }

        private void nud_nfly1_ValueChanged(object sender, EventArgs e)
        {

        }

        private void nud_nfly1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                GlobalVar.closeSave.curFly1Count = (int)nud_nfly1.Value;
            }
        }

        private void nud_nfly2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                GlobalVar.closeSave.curFly2Count = (int)nud_nfly2.Value;
            }
        }

        private void ckb_IsManThrough_CheckedChanged(object sender, EventArgs e)
        {
            GlobalVar.IsManThrought = ckb_IsManThrough.Checked;
        }

        private void btn_ManSignal_Click(object sender, EventArgs e)
        {
            GlobalVar.IsManFinishSignal = true;
        }

        private void ckb_isThrough_CheckedChanged(object sender, EventArgs e)
        {
            GlobalVar.IsThrought = ckb_isThrough.Checked;
        }

        private void btn_fly1Clear_Click(object sender, EventArgs e)
        {
            GlobalVar.closeSave.curFly1Count = 0;
            nud_nfly1.Value = 0;
        }

        private void btn_fly2Clear_Click(object sender, EventArgs e)
        {
            GlobalVar.closeSave.curFly2Count = 0;
            nud_nfly2.Value = 0;
        }
        private int btn_HomeProccess(string reset)
        {

            this.Invoke(new Action(() =>
            {
                btn_Home_Click(btn_Home, null);
            }));
            return 1;
        }
        private int btn_StartProccess(string reset)
        {
            this.Invoke(new Action(() =>
            {
                btn_start_Click(btn_start, null);
            }));
            return 1;
        }
        private int btn_EstopProccess(string stop)
        {

            this.Invoke(new Action(() =>
            {
                btn_AburptStop_Click(btn_start, null);
            }));
            return 1;
        }
        private void button1_Click_1(object sender, EventArgs e)
        {
            GlobalVar.front_pros = new List<ProductInfo>();
            GlobalVar.front_pros.Add(new ProductInfo()
            {
                LaserTime = DateTime.Now,
                typeName = GlobalVar.closeSave.CurrentTypeName,
                ProId = "O1",
                ProNo = 1,
                IsProcessAlarm = 1,
                Result_up = e_Result.进料OK.ToString()
            });
            GlobalVar.front_pros.Add(new ProductInfo()
            {
                LaserTime = DateTime.Now,
                typeName = GlobalVar.closeSave.CurrentTypeName,
                ProId = "O1",
                ProNo = 2,
                IsProcessAlarm = 1,
                Result_up = e_Result.进料OK.ToString()
            });
        }
    }
}
